package hr.bean;

import java.util.ArrayList;
import hr.dao.BranchDAO;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ActionEvent;

import resources.pojo.hr_branch;
import resources.util.Tool;

@ManagedBean(name="branch")
@SessionScoped
public class Branch {
	private int currentPage;
	private hr_branch branch;

	private hr_branch selectedBranch;
	private String nameSearch;
	private ArrayList<hr_branch> listBranch;
	private Integer[] pages;
	private String last;
	
	public void onload() {
		if(!Tool.isPostBack()){
			init();
		}
	}
	
	public void initObject(){
		if(!Tool.isPostBack()){
			branch = new hr_branch();
		}
	}
	
	public void init(){
		currentPage = 1;
		nameSearch="";
		branch = new hr_branch();
		listBranch = BranchDAO.getListBranchPaging("",currentPage,Tool.max_row);
		setPages(Tool.getPages());
	}
	
	public void paging(){
		listBranch = BranchDAO.getListBranchPaging("",currentPage,Tool.max_row);
		setPages(Tool.getPages());
	}
	
	public void insert(){
		branch.setId("BRA" + Tool.generateID());
		branch.setStatus(1);
		String result = BranchDAO.action("insert",branch,0);
		if(result.equals("completed")){
		}else if(result.equals("duplicate")){
			Tool.message("Tên phòng ban không được trùng nhau");
		}
		init();
	}
	
	public void update(){
		String result = BranchDAO.action("update",selectedBranch,last.equals(selectedBranch.getName())?1:0);
		if(result.equals("completed")){
		}else if(result.equals("duplicate")){
			Tool.message("Tên phòng ban không được trùng nhau");
			selectedBranch = new hr_branch();
		}
		init();
	}
	
	public void choose(ActionEvent event){
		selectedBranch = (hr_branch) event.getComponent().getAttributes().get("object");
		last=selectedBranch.getName();
	}
	
	public void search(){
		listBranch = BranchDAO.getListBranchPaging(nameSearch,1,Tool.max_row);
		setPages(Tool.getPages());
	}
	
	public void nextPage(){
		currentPage ++;
	}

	public String getNameSearch() {
		return nameSearch;
	}

	public void setNameSearch(String nameSearch) {
		this.nameSearch = nameSearch;
	}

	public int getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	public void setPages(Integer[] pages) {
		this.pages = pages;
	}

	public Integer[] getPages() {
		return pages;
	}

	public hr_branch getBranch() {
		return branch;
	}

	public void setBranch(hr_branch branch) {
		this.branch = branch;
	}

	public hr_branch getSelectedBranch() {
		return selectedBranch;
	}

	public void setSelectedBranch(hr_branch selectedBranch) {
		this.selectedBranch = selectedBranch;
	}

	public ArrayList<hr_branch> getListBranch() {
		return listBranch;
	}

	public void setListBranch(ArrayList<hr_branch> listBranch) {
		this.listBranch = listBranch;
	}

}
